package com.wlz.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wlz
 * @date 2022-07-07  10:47 下午
 */
@Slf4j
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {


    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        String msg = "【客户端】 " + channel.remoteAddress() + " 上线了 " + sdf.format(new Date());
        channels.writeAndFlush(msg);

        channels.add(channel);

        String serverMsg = channel.remoteAddress() + "上线了。。。";
        log.info(serverMsg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        String msg = "【客户端】 " + channel.remoteAddress() + " 下线了 " + sdf.format(new Date());
        channels.writeAndFlush(msg);

        String serverMsg = channel.remoteAddress() + "下线了。。。";
        log.info(serverMsg);
        log.info(" channels size : {}", channels.size());

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channels.forEach(ch -> {
            if (ch != channel) {
                ch.writeAndFlush("【客户端】 " + channel.remoteAddress() + " 发送了消息  " + msg);
            }else {
                ch.writeAndFlush("【自己 】  发送了消息  " + msg);
            }
        });
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 关闭通道
        ctx.close();
    }
}
